<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据源名称" prop="dsName">
        <el-input
          v-model="queryParams.dsName"
          placeholder="请输入数据源名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源类型" prop="dsType">
        <el-select v-model="queryParams.dsType" placeholder="请选择数据源类型" clearable size="small">
          <el-option label="MySQL" value="mysql" />
          <el-option label="Oracle" value="oracle" />
          <el-option label="PostgreSQL" value="postgresql" />
          <el-option label="SQL Server" value="sqlserver" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="dsStatus">
        <el-select v-model="queryParams.dsStatus" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rpt:datasource:create']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rpt:datasource:update']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rpt:datasource:delete']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据源ID" align="center" prop="dsId" v-if="false" />
      <el-table-column label="数据源名称" align="center" prop="dsName" />
      <el-table-column label="数据源类型" align="center" prop="dsType">
        <template slot-scope="scope">
          {{ getDsTypeText(scope.row.dsType) }}
        </template>
      </el-table-column>
      <el-table-column label="连接URL" align="center" prop="dsUrl" :show-overflow-tooltip="true" />
      <el-table-column label="用户名" align="center" prop="dsUsername" />
      <el-table-column label="状态" align="center" prop="dsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.dsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rpt:datasource:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rpt:datasource:delete']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handleTest(scope.row)"
            v-hasPermi="['rpt:datasource:query']"
          >测试连接</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="数据源名称" prop="dsName">
          <el-input v-model="form.dsName" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="dsType">
          <el-select v-model="form.dsType" placeholder="请选择数据源类型">
            <el-option label="MySQL" value="mysql" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQL Server" value="sqlserver" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接URL" prop="dsUrl">
          <el-input v-model="form.dsUrl" placeholder="请输入连接URL" />
        </el-form-item>
        <el-form-item label="用户名" prop="dsUsername">
          <el-input v-model="form.dsUsername" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="dsPassword">
          <el-input v-model="form.dsPassword" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="dsStatus">
          <el-radio-group v-model="form.dsStatus">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDatasource, getDatasource, delDatasource, addDatasource, updateDatasource, testDatasource } from "@/api/report/datasource";

export default {
  name: "DataSource",
  dicts: ['common_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据源表格数据
      datasourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dsName: undefined,
        dsType: undefined,
        dsStatus: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dsName: [
          { required: true, message: "数据源名称不能为空", trigger: "blur" }
        ],
        dsType: [
          { required: true, message: "数据源类型不能为空", trigger: "change" }
        ],
        dsUrl: [
          { required: true, message: "连接URL不能为空", trigger: "blur" }
        ],
        dsUsername: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        dsPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据源列表 */
    getList() {
      this.loading = true;
      listDatasource(this.queryParams).then(response => {
        this.datasourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取数据源类型文本
    getDsTypeText(type) {
      const typeMap = {
        mysql: 'MySQL',
        oracle: 'Oracle',
        postgresql: 'PostgreSQL',
        sqlserver: 'SQL Server'
      };
      return typeMap[type] || type;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dsId: undefined,
        dsName: undefined,
        dsType: 'mysql',
        dsUrl: undefined,
        dsUsername: undefined,
        dsPassword: undefined,
        dsStatus: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据源";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dsId = row.dsId || this.ids[0];
      getDatasource(dsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据源";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dsId != null) {
            updateDatasource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDatasource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dsIds = row.dsId || this.ids;
      this.$modal.confirm('是否确认删除数据源编号为"' + dsIds + '"的数据项?').then(function() {
        return delDatasource(dsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 测试连接按钮操作 */
    handleTest(row) {
      testDatasource(row).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("连接成功");
        } else {
          this.$modal.msgError("连接失败: " + response.msg);
        }
      }).catch(() => {});
    }
  }
};
</script> 